package com.yamanyar.weebill.view;

import java.io.Serializable;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;

import com.yamanyar.weebill.domain.User;
import com.yamanyar.weebill.service.UserService;

/**
 * Creates an User.
 * 
 * Created in Jun 28, 2008.
 * 
 * @author Kaan Yamanyar
 */
@org.springframework.stereotype.Component("createUser")
@Scope("request")
public class CreateUser implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 6785907946599065081L;

	private UserService userService;

	private User user = new User();

	@Autowired
	public CreateUser(UserService projectService) {
		this.userService = projectService;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public String save() {
		// set password to 1234 if the password is not set already!
		if (user.getPassword() == null)
			user.setPassword("1234");

		try {
			userService.createNew(user);
			FacesMessage facesMessage = new FacesMessage(
					FacesMessage.SEVERITY_INFO, "User is saved successfully",
					"OK");
			FacesContext.getCurrentInstance().addMessage(null, facesMessage);
		} catch (javax.persistence.EntityExistsException eee) {
			FacesMessage facesMessage = new FacesMessage(
					FacesMessage.SEVERITY_ERROR, "User already exits!", "OK");
			FacesContext.getCurrentInstance().addMessage(null, facesMessage);

		}

		user = new User();
		return null;
	}
}
